package com.itheima.zookeeper;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

public class ZookeeperTest1 {

    //创建zookeeper节点
    @Test
    public void test1() throws Exception{
        //zookeeper客户端对象
        String connectString="192.168.88.6:2181,192.168.88.7:2181,192.168.88.8:2181";
        ExponentialBackoffRetry retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework zookeeperClient = CuratorFrameworkFactory.newClient(connectString,retryPolicy);

        //2、启动客户端
        zookeeperClient.start();

        //3、执行相关操作
        zookeeperClient.create().withMode(CreateMode.PERSISTENT).forPath("/test3","hellozookeeper".getBytes());

        //4、释放资源
        zookeeperClient.close();
    }


    @Test
    public void test2() throws Exception{
        //创建客户端
        String connStr="192.168.88.6:2181,192.168.88.7:2181,192.168.88.8:2181";
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000,3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(connStr,retry);


        //启动客户端
        client.start();

        //修改数据
        client.setData().forPath("/test2","liuqiaihaozhi".getBytes());

        client.close();
    }

    @Test //删除数据
    public void test3() throws Exception{
        //创建客户端
        String connStr="192.168.88.6:2181,192.168.88.7:2181,192.168.88.8:2181";
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000,3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(connStr,retry);


        //启动客户端
        client.start();

        //修改数据
        //client.delete().deletingChildrenIfNeeded().forPath("");//删除有子结点的结点
        client.delete().forPath("/test3");

        client.close();
    }


    @Test//查询
    public void test4() throws Exception{
        //创建客户端
        String connStr="192.168.88.6:2181,192.168.88.7:2181,192.168.88.8:2181";
        ExponentialBackoffRetry retry = new ExponentialBackoffRetry(1000,3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(connStr,retry);

        //启动客户端
        client.start();

        //查询
        byte[] bytes = client.getData().forPath("/test2");
        String s = new String(bytes);
        System.out.println(s);

        client.close();
    }

}

